package filex

import (
	"crypto/md5"
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"io"
	"os"
	"os/exec"
)

// JoinFile 文件名拼接
// name: 文件名
// ext: 文件扩展名
func JoinFile(name string, ext string) string {
	return fmt.Sprintf("%s.%s", name, ext)
}

// Move 文件移动
func Move(src string, dst string) error {
	cmd := exec.Command("mv", src, dst)
	if _, err := cmd.Output(); err != nil {
		return err
	}
	return nil
}

// MD5 计算文件MD5
// size: 单次读取文件大小
func MD5(path string, size ...uint64) (string, error) {
	file, err := os.Open(path)
	if err != nil {
		return "", err
	}
	defer func(file *os.File) {
		_ = file.Close()
	}(file)

	hash := md5.New()

	if size == nil {
		/* 默认 1024 * 1024 */
		size = append(size, 1024*1024)
	}
	buffer := make([]byte, size[0])

	if _, err = io.CopyBuffer(hash, file, buffer); err != nil {
		return "", err
	}
	return hex.EncodeToString(hash.Sum(nil)), nil
}

// SHA256 计算文件SHA256
// size: 单次读取文件大小
func SHA256(path string, size ...uint64) (string, error) {
	file, err := os.Open(path)
	if err != nil {
		return "", err
	}
	defer func(file *os.File) {
		_ = file.Close()
	}(file)

	hash := sha256.New()

	if size == nil {
		/* 默认 1024 * 1024 */
		size = append(size, 1024*1024)
	}
	buffer := make([]byte, size[0])

	if _, err = io.CopyBuffer(hash, file, buffer); err != nil {
		return "", err
	}
	return hex.EncodeToString(hash.Sum(nil)), nil
}
